<?php
namespace app\admin\controller;

use app\admin\tool\Parser;
use think\Request;
use app\common\model\Upload as UploadModel;
use app\common\model\Address as AddressModel;
use PHPQRCode\QRcode;

/**
 * 系统的后台接口调用
 * Class Api
 * @package app\admin\controller
 */
class Api extends Base {

    /**
     * 图片上传接口 后期加一个数据库保存 如此可以方便查找
     * @param Request $request
     * @return string
     */
    public function upload(Request $request){
        $file = $request->file('file');
        $data = [];
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

            if($info){
                $data['ext'] =  $info->getExtension();
                $data['name'] = $info->getSaveName();
                $data["filename"] =  $info->getFilename();
                $data['url'] = "/uploads".DS.$info->getSaveName();
                $data['status'] = 'success';

                $file_info = $info->getInfo();
                //保存
                UploadModel::create([
                    'filename'=>$data['filename'],
                    'origin_name'=>$file_info['name'],//原本的名称
                    'url'=>$data['url'],
                    'ext'=>$data['ext'],
                    'type'=>'1',
                    'size'=>$file_info['size'],
                    'op_user'=>$this->admin->id,
                    'add_time'=>time()
                ]);
            }else{
                // 上传失败获取错误信息
                $data['error'] = $file->getError();
                $data['status'] = 'error';
            }
        }
        return json_encode($data);
    }


    /**
     * 获取推广二维码
     */
    public function getInviteQr(Request $request){
        $refresh = $request->param('refresh');
        $code = $request->param("code");
        $path = "uploads/123".$code.'png';
        if(!file_exists($path) || $refresh == 1){
            $text = "https://xcx.ogmall.com/index/index/index/invite/".$code;
            $size = 6;
            Qrcode::png($text, $path, $size);
        }
        ob_end_clean();
        header("Content-Type:image/png");
        echo file_get_contents($path);
    }
}
